<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>温度趋势分析 | WeatherViz Pro</title>
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.2/dist/echarts.min.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" rel="stylesheet">
    <style>
        :root {
            --bg-primary: #f5f5f5;         /* 浅灰色背景 */
            --bg-secondary: #ffffff;       /* 白色卡片 */
            --primary-color: #333333;       /* 主色-深灰色 */
            --secondary-color: #555555;     /* 辅助色-中灰色 */
            --accent-color: #e74c3c;        /* 强调色-暗红色 */
            --light-text: #777777;          /* 浅色文本 */
            --medium-text: #999999;         /* 中等文本色 */
            --border-color: #eeeeee;        /* 边框色 */
            --shadow: 0 2px 8px rgba(0, 0, 0, 0.05); /* 柔和阴影 */
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Microsoft YaHei', sans-serif;
            transition: all 0.3s ease;
        }

        body {
            background: var(--bg-primary);
            color: var(--primary-color);
            line-height: 1.6;
            overflow-x: hidden;
        }

        .container {
            width: 90%;
            max-width: 1200px;
            margin: 30px auto;
            padding: 25px;
            border-radius: 10px;
            background: var(--bg-secondary);
            box-shadow: var(--shadow);
        }

        h2 {
            text-align: center;
            color: var(--primary-color);
            font-size: 2rem;
            margin-bottom: 2rem;
            padding: 1rem 0;
            border-bottom: 2px solid var(--border-color);
        }

        .glass-panel {
            background: var(--bg-secondary);
            border-radius: 10px;
            padding: 2rem;
            margin-bottom: 2rem;
            border: 1px solid var(--border-color);
        }

        .controls {
            display: flex;
            flex-wrap: wrap;
            gap: 1.5rem;
            margin-bottom: 2rem;
            justify-content: center;
        }

        select {
            padding: 0.8rem 1.5rem;
            background: var(--bg-primary);
            color: var(--primary-color);
            border: 1px solid var(--border-color);
            border-radius: 6px;
            outline: none;
            appearance: none;
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%23333333'%3E%3Cpath d='M7 10l5 5 5-5z'/%3E%3C/svg%3E");
            background-repeat: no-repeat;
            background-position: right 15px center;
            background-size: 16px;
            font-size: 1rem;
        }

        select:hover {
            border-color: var(--secondary-color);
        }

        select:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 2px rgba(51, 51, 51, 0.1);
        }

        label {
            color: var(--secondary-color);
            font-size: 1rem;
            margin-right: 0.8rem;
            font-weight: 500;
        }

        #temperatureChart {
            width: 100%;
            height: 550px;
            border-radius: 10px;
            background: var(--bg-primary);
            border: 1px solid var(--border-color);
            margin-bottom: 20px;
        }

        .return-button {
            position: fixed;
            top: 20px;
            right: 20px;
            background: var(--bg-secondary);
            color: var(--primary-color);
            padding: 0.8rem 1.5rem;
            border-radius: 6px;
            border: 1px solid var(--border-color);
            text-decoration: none;
            display: flex;
            align-items: center;
            font-size: 1rem;
            z-index: 1000;
        }

        .return-button:hover {
            background: var(--bg-primary);
            border-color: var(--secondary-color);
        }

        .return-button i {
            margin-right: 0.5rem;
        }

        .data-explanation {
            background: var(--bg-primary);
            border-radius: 10px;
            padding: 1.5rem;
            border-left: 3px solid var(--primary-color);
            margin-top: 1.5rem;
        }

        .explanation-title {
            font-size: 1.2rem;
            color: var(--primary-color);
            margin-bottom: 1rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .explanation-content {
            color: var(--light-text);
            line-height: 1.8;
        }

        .stat-highlight {
            color: var(--accent-color);
            font-weight: 600;
        }

        .season-box {
            background: var(--bg-secondary);
            border-radius: 8px;
            padding: 1rem;
            margin: 1rem 0;
            border-left: 3px solid var(--secondary-color);
        }

        @media (max-width: 768px) {
            .controls {
                flex-direction: column;
                align-items: center;
            }

            select {
                min-width: 100%;
            }

            #temperatureChart {
                height: 450px;
            }

            h2 {
                font-size: 1.6rem;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <h2>温度趋势分析</h2>

        <div class="glass-panel">
            <div class="controls">
                <div>
                    <label for="citySelect">城市：</label>
                    <select id="citySelect">
                        {% for city in cities %}
                            <option value="{{ city }}" {% if city == urban %}selected{% endif %}>{{ city }}</option>
                        {% endfor %}
                    </select>
                </div>

                <div>
                    <label for="yearSelect">年份：</label>
                    <select id="yearSelect">
                        <option value="">全部</option>
                        {% for year in years %}
                            <option value="{{ year }}">{{ year }} 年</option>
                        {% endfor %}
                    </select>
                </div>
            </div>

            <div id="temperatureChart"></div>

            <div class="data-explanation" id="explanationSection">
                <h3 class="explanation-title">
                    <i class="fas fa-chart-line"></i> 温度趋势分析
                </h3>
                <div class="explanation-content" id="explanationContent">
                    请选择城市和年份以查看温度趋势分析
                </div>
            </div>
        </div>
    </div>

    <a href="#" class="return-button">
        <i class="fas fa-arrow-left"></i> 返回首页
    </a>

    <script>
        // 自定义ECharts主题 - 朴素风格
        const simpleTheme = {
            color: [
                '#333333', '#555555', '#e74c3c',
                '#3498db', '#2ecc71', '#f39c12',
                '#7f8c8d', '#9b59b6', '#1abc9c'
            ],
            backgroundColor: '#f5f5f5',
            textStyle: {
                color: '#333333'
            },
            title: {
                textStyle: {
                    color: '#333333',
                    fontFamily: 'Microsoft YaHei, sans-serif',
                    fontSize: 18
                }
            },
            tooltip: {
                backgroundColor: 'rgba(255, 255, 255, 0.9)',
                borderColor: '#eeeeee',
                borderWidth: 1,
                textStyle: {
                    color: '#333333'
                },
                axisPointer: {
                    lineStyle: {
                        color: '#dddddd',
                        width: 1,
                        type: 'dashed'
                    }
                }
            },
            legend: {
                textStyle: {
                    color: '#555555'
                }
            },
            xAxis: {
                axisLine: {
                    lineStyle: {
                        color: '#eeeeee'
                    }
                },
                axisTick: {
                    lineStyle: {
                        color: '#eeeeee'
                    }
                },
                axisLabel: {
                    textStyle: {
                        color: '#777777'
                    }
                },
                splitLine: {
                    lineStyle: {
                        color: '#f0f0f0'
                    }
                }
            },
            yAxis: {
                axisLine: {
                    lineStyle: {
                        color: '#eeeeee'
                    }
                },
                axisTick: {
                    lineStyle: {
                        color: '#eeeeee'
                    }
                },
                axisLabel: {
                    textStyle: {
                        color: '#777777'
                    }
                },
                splitLine: {
                    lineStyle: {
                        color: '#f0f0f0'
                    }
                }
            },
            grid: {
                borderColor: '#f0f0f0'
            },
            line: {
                itemStyle: {
                    borderWidth: 2
                },
                lineStyle: {
                    width: 2,
                    color: '#333333'
                },
                emphasis: {
                    lineStyle: {
                        width: 3
                    }
                }
            },
            dataZoom: {
                handleStyle: {
                    color: '#333333',
                    borderColor: '#dddddd'
                },
                textStyle: {
                    color: '#777777'
                }
            }
        };

        // 注册自定义主题
        echarts.registerTheme('simple', simpleTheme);

        const temperatureChartDom = document.getElementById('temperatureChart');
        const temperatureChart = echarts.init(temperatureChartDom, 'simple');

        // 城市气候特征库
        const CITY_CLIMATE = {
            "北京": {
                name: "北京",
                climate: "温带季风气候",
                description: "夏季高温多雨，冬季寒冷干燥，四季分明。年均温11-13℃，夏季（7月）平均最高温约26-30℃，冬季（1月）平均最低温约-5至-10℃。",
                seasons: {
                    summer: { months: [6, 7, 8], desc: "高温多雨，7月温度达到峰值" },
                    winter: { months: [12, 1, 2], desc: "寒冷干燥，1月温度最低" }
                }
            },
            "上海": {
                name: "上海",
                climate: "亚热带季风气候",
                description: "夏季炎热湿润，冬季温和少雨，春秋较短。年均温15-18℃，夏季（7月）平均最高温约27-32℃，冬季（1月）平均最低温约3-8℃。",
                seasons: {
                    summer: { months: [6, 7, 8], desc: "炎热湿润，7-8月易受台风影响" },
                    winter: { months: [12, 1, 2], desc: "温和少雨，1月温度最低" }
                }
            },
            "广州": {
                name: "广州",
                climate: "亚热带季风气候",
                description: "全年温暖湿润，夏季长而炎热，冬季短暂温和。年均温21-23℃，夏季（7月）平均最高温约28-33℃，冬季（1月）平均最低温约10-15℃。",
                seasons: {
                    summer: { months: [5, 6, 7, 8, 9], desc: "漫长夏季，高温多雨，7月温度最高" },
                    winter: { months: [12, 1, 2], desc: "短暂温和，1月温度最低" }
                }
            },
            "哈尔滨": {
                name: "哈尔滨",
                climate: "温带大陆性季风气候",
                description: "夏季凉爽短促，冬季寒冷漫长，温差较大。年均温3-5℃，夏季（7月）平均最高温约22-26℃，冬季（1月）平均最低温约-15至-25℃。",
                seasons: {
                    summer: { months: [6, 7, 8], desc: "凉爽短促，7月温度最高" },
                    winter: { months: [11, 12, 1, 2, 3], desc: "寒冷漫长，1月温度最低" }
                }
            },
            "成都": {
                name: "成都",
                climate: "亚热带季风气候",
                description: "全年温和湿润，夏季多雨，冬季少雪，多云雾。年均温15-17℃，夏季（7月）平均最高温约25-29℃，冬季（1月）平均最低温约4-8℃。",
                seasons: {
                    summer: { months: [6, 7, 8], desc: "多雨季节，7月温度最高" },
                    winter: { months: [12, 1, 2], desc: "少雪湿润，1月温度最低" }
                }
            },
            "_default": {
                name: "未知城市",
                climate: "未收录气候",
                description: "该城市气候特征暂未收录，以下为温度数据分析。",
                seasons: {}
            }
        };

        // 存储所有年份的数据缓存
        let allYearsTemperatureData = {};
        let currentCity = "";
        let currentYear = "";

        function updateCharts(city, year) {
            currentCity = city;
            currentYear = year;
            // 温度趋势图
            updateTemperatureChart(city, year);
            // 更新数据分析
            updateDataExplanation(city, year);
        }

        function updateTemperatureChart(city, year) {
            // 如果已经缓存了该城市的所有年份数据，并且当前请求全部年份，则直接使用缓存
            if (year === "" && allYearsTemperatureData[city]) {
                renderAllYearsTemperatureChart(city);
                return;
            }

            // 模拟数据请求（实际应用中请替换为真实API）
            const mockData = generateMockTemperatureData(city, year);

            // 处理单一年份数据
            const seriesData = mockData.months.map((month, index) => ({
                name: month,
                value: mockData.temperatures[index]
            }));

            const option = {
                title: {
                    text: `${city} ${year} 年月度平均温度趋势`,
                    left: 'center'
                },
                tooltip: {
                    trigger: 'axis',
                    backgroundColor: 'rgba(255, 255, 255, 0.9)',
                    borderColor: '#eeeeee',
                    borderWidth: 1,
                    textStyle: {
                        color: '#333333'
                    },
                    axisPointer: {
                        type: 'line',
                        lineStyle: {
                            color: '#dddddd',
                            width: 1,
                            opacity: 0.8
                        }
                    }
                },
                xAxis: {
                    type: 'category',
                    data: mockData.months.map(m => m.split('-')[1] + '月'), // 只显示月份
                    axisLine: {
                        lineStyle: {
                            color: '#eeeeee'
                        }
                    },
                    axisLabel: {
                        textStyle: {
                            color: '#777777'
                        }
                    }
                },
                yAxis: {
                    type: 'value',
                    name: '平均温度 (°C)',
                    nameTextStyle: {
                        color: '#555555'
                    },
                    axisLine: {
                        lineStyle: {
                            color: '#eeeeee'
                        }
                    },
                    axisLabel: {
                        textStyle: {
                            color: '#777777'
                        }
                    }
                },
                series: [{
                    name: `${year}年`,
                    type: 'line',
                    data: seriesData,
                    showSymbol: true,
                    symbol: 'circle',
                    symbolSize: 6,
                    itemStyle: {
                        color: '#333333',
                        borderWidth: 1,
                        borderColor: '#ffffff'
                    },
                    lineStyle: {
                        width: 2,
                        color: '#333333'
                    },
                    areaStyle: {
                        color: {
                            type: 'linear',
                            x: 0, y: 0, x2: 0, y2: 1,
                            colorStops: [{
                                offset: 0, color: 'rgba(51, 51, 51, 0.1)'
                            }, {
                                offset: 1, color: 'rgba(51, 51, 51, 0)'
                            }],
                            global: false
                        }
                    }
                }]
            };

            temperatureChart.setOption(option, true);
        }

        // 生成模拟温度数据（实际应用中请替换为真实数据）
        function generateMockTemperatureData(city, year) {
            const baseTemps = {
                "北京": [ -5, -3, 5, 12, 20, 25, 28, 26, 20, 15, 8, 2 ],
                "上海": [ 3, 5, 10, 16, 22, 27, 30, 29, 24, 18, 12, 6 ],
                "广州": [ 10, 12, 18, 23, 28, 32, 33, 32, 29, 25, 20, 15 ],
                "哈尔滨": [ -20, -18, -8, 5, 15, 22, 25, 23, 15, 8, -5, -15 ],
                "成都": [ 4, 6, 12, 18, 23, 27, 29, 28, 23, 18, 12, 7 ],
                "_default": [ 10, 12, 15, 20, 25, 30, 32, 31, 27, 22, 16, 12 ]
            };

            const cityKey = CITY_CLIMATE[city] ? city : "_default";
            const baseTemp = baseTemps[cityKey] || baseTemps["_default"];

            // 生成带年份的月份数据
            const months = [];
            for (let i = 1; i <= 12; i++) {
                months.push(`${year}-${i.toString().padStart(2, '0')}`);
            }

            // 生成温度数据（添加随机波动）
            const temperatures = baseTemp.map(t => Math.round(t + (Math.random() - 0.5) * 3));

            return {
                months: months,
                temperatures: temperatures
            };
        }

        // 渲染所有年份温度数据的图表
        function renderAllYearsTemperatureChart(city) {
            // 生成过去5年的模拟数据
            const years = [];
            const currentYear = new Date().getFullYear();
            for (let i = 0; i < 5; i++) {
                years.push(currentYear - i);
            }

            // 创建系列数据
            const series = years.map(year => ({
                name: `${year}年`,
                type: 'line',
                data: generateMockTemperatureData(city, year).temperatures,
                showSymbol: true,
                symbol: 'circle',
                symbolSize: 5,
                smooth: true,
                lineStyle: {
                    width: 2
                },
                areaStyle: {
                    opacity: 0.05
                }
            }));

            // X轴月份标签（中文格式）
            const xAxisData = Array.from({ length: 12 }, (_, i) => `${i + 1}月`);

            const option = {
                title: {
                    text: `${city} 近5年月度平均温度趋势`,
                    left: 'center'
                },
                tooltip: {
                    trigger: 'axis',
                    backgroundColor: 'rgba(255, 255, 255, 0.9)',
                    borderColor: '#eeeeee',
                    borderWidth: 1,
                    textStyle: {
                        color: '#333333'
                    },
                    axisPointer: {
                        type: 'cross',
                        lineStyle: {
                            color: '#dddddd',
                            width: 1,
                            opacity: 0.8
                        }
                    }
                },
                legend: {
                    type: 'scroll',
                    bottom: 10,
                    textStyle: {
                        color: '#555555'
                    }
                },
                xAxis: {
                    type: 'category',
                    data: xAxisData,
                    axisLine: {
                        lineStyle: {
                            color: '#eeeeee'
                        }
                    },
                    axisLabel: {
                        textStyle: {
                            color: '#777777'
                        }
                    }
                },
                yAxis: {
                    type: 'value',
                    name: '平均温度 (°C)',
                    nameTextStyle: {
                        color: '#555555'
                    },
                    axisLine: {
                        lineStyle: {
                            color: '#eeeeee'
                        }
                    },
                    axisLabel: {
                        textStyle: {
                            color: '#777777'
                        }
                    }
                },
                series: series
            };

            temperatureChart.setOption(option, true);
        }

        // 更新数据分析内容
        function updateDataExplanation(city, year) {
            const explanationContent = document.getElementById('explanationContent');
            const explanationSection = document.getElementById('explanationSection');

            if (!city) {
                explanationContent.innerHTML = "请选择城市和年份以查看温度趋势分析";
                explanationSection.style.display = "block";
                return;
            }

            // 获取城市气候特征
            const cityInfo = CITY_CLIMATE[city] || CITY_CLIMATE["_default"];
            const isAllYears = year === "";
            const yearText = isAllYears ? "近5年平均" : `${year}年`;

            // 构建基础解释内容
            let content = `<p>以下是${cityInfo.name}${yearText}的温度趋势分析，数据反映了${cityInfo.name}的温度季节变化规律和${isAllYears ? "长期" : "当年"}气候特征。</p>`;

            // 添加气候特征
            content += `<div class="season-box">
                <p><strong>气候特征：</strong>${cityInfo.climate}，${cityInfo.description}</p>
            </div>`;

            // 生成模拟分析数据
            const mockData = generateMockTemperatureData(city, year);
            const temps = mockData.temperatures;
            const avgTemp = temps.reduce((sum, v) => sum + v, 0) / temps.length;
            const maxTemp = Math.max(...temps);
            const minTemp = Math.min(...temps);
            const maxMonth = mockData.months[temps.indexOf(maxTemp)].split('-')[1] + '月';
            const minMonth = mockData.months[temps.indexOf(minTemp)].split('-')[1] + '月';

            content += `<p><strong>温度统计：</strong>${yearText}${cityInfo.name}的月均温度为${avgTemp.toFixed(1)}℃，其中${maxMonth}达到${maxTemp.toFixed(1)}℃（最高温），${minMonth}为${minTemp.toFixed(1)}℃（最低温），温差达${(maxTemp - minTemp).toFixed(1)}℃。</p>`;

            // 季节分析
            if (cityInfo.seasons.summer && cityInfo.seasons.winter) {
                const summerMonths = cityInfo.seasons.summer.months;
                const winterMonths = cityInfo.seasons.winter.months;

                let summerTempSum = 0;
                let summerCount = 0;
                let winterTempSum = 0;
                let winterCount = 0;

                mockData.months.forEach((m, index) => {
                    const monthNum = parseInt(m.split('-')[1]);
                    if (summerMonths.includes(monthNum)) {
                        summerTempSum += temps[index];
                        summerCount++;
                    }
                    if (winterMonths.includes(monthNum)) {
                        winterTempSum += temps[index];
                        winterCount++;
                    }
                });

                const summerAvg = summerCount > 0 ? summerTempSum / summerCount : 0;
                const winterAvg = winterCount > 0 ? winterTempSum / winterCount : 0;

                content += `<div class="season-box">
                    <p><strong>季节温度特征：</strong>${cityInfo.name}${yearText}夏季（${summerMonths.join('/')}月）平均温度为${summerAvg.toFixed(1)}℃，${cityInfo.seasons.summer.desc}；冬季（${winterMonths.join('/')}月）平均温度为${winterAvg.toFixed(1)}℃，${cityInfo.seasons.winter.desc}。</p>
                </div>`;
            }

            explanationContent.innerHTML = content;
            explanationSection.style.display = "block";
        }

        const citySelect = document.getElementById('citySelect');
        const yearSelect = document.getElementById('yearSelect');

        citySelect.addEventListener('change', () => {
            const selectedCity = citySelect.value;
            const selectedYear = yearSelect.value;
            updateCharts(selectedCity, selectedYear);
        });

        yearSelect.addEventListener('change', () => {
            const selectedCity = citySelect.value;
            const selectedYear = yearSelect.value;
            updateCharts(selectedCity, selectedYear);
        });

        // 初始化图表
        const initialCity = "{{ urban }}";
        const initialYear = ""; // 默认显示全部年份
        updateCharts(initialCity, initialYear);

        // 监听窗口大小变化，调整图表尺寸
        window.addEventListener('resize', () => {
            temperatureChart.resize();
        });
    </script>
</body>
</html>